package org.schhx.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.schhx.session.Configuration;
import org.schhx.session.MappedStatement;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shanchao
 * @date 2021/1/30
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element root = document.getRootElement();
        String namespace = root.attributeValue("namespace");

        List<Element> elements = new ArrayList<>();
        elements.addAll(root.selectNodes("select"));
        elements.addAll(root.selectNodes("update"));
        elements.addAll(root.selectNodes("insert"));
        elements.addAll(root.selectNodes("delete"));

        for (Element element : elements) {
            parseStatement(namespace, element);
        }
    }

    private void parseStatement(String namespace, Element parent) {
        String id = parent.attributeValue("id");
        String parameterType = parent.attributeValue("parameterType");
        String resultType = parent.attributeValue("resultType");
        String statementId = String.format("%s.%s", namespace, id);
        String sql = parent.getTextTrim();
        MappedStatement mappedStatement = new MappedStatement();
        mappedStatement.setParameterType(parameterType);
        mappedStatement.setResultType(resultType);
        mappedStatement.setSql(sql);
        mappedStatement.setOperateType("select".equals(parent.getName()) ? "select" : "update");
        mappedStatement.setConfiguration(configuration);

        configuration.addMappedStatement(statementId, mappedStatement);
    }
}
